<template>
	<view class="page">
		<cu-custom bgColor="bg-white" :isBack="false" :backText="true"><block slot="backText" @tap="changeEdit">{{izEdit && cartList.length>0?'编辑':'管理'}}</block><block slot="content">购物车</block></cu-custom>
		<mescroll-uni ref="mescrollRef" @init="mescrollInit" height="90%" top="0" :down="downOption" @down="downCallback" :up="upOption" @up="upCallback" @emptyclick="emptyClick">
			<view style="height: 100%;padding-bottom: 30px;">
				<view class="cu-list menu card-menu margin-top margin-bottom-sm" v-for="(seller,index) in cartList" :key="index" >
					<view class="cu-item"  style="padding-top: 10px;">
						<view class="content flex align-center">
							<view class="flex align-center">
								<text class="cuIcon-shop text-theme" style="font-size: 18px;"></text>
								<text class="text-black text-bold text-df margin-left-sm" style="flex:1; line-height: 32rpx;">{{seller.seller_name}}</text>
							</view>
						</view>
					</view>
					<view class="cu-list menu move-cur bg-white">
						<view class="cu-item flex-wrap bg-white margin-bottom-xs" style="padding:10px 10px; " v-for="(sku,index1) in seller.sku_list" :key="index1" 
						@touchstart="ListTouchStart" @touchmove="ListTouchMove" 
						@touchend="ListTouchEnd" :data-target="'move-box-' + index+index1" :class="modalName=='move-box-'+ index+index1?'move-cur':''">
							<view class="margin-right-sm">
							  <icon v-if="sku.checked===1" type="success" color="#CB1414" @tap="sigleCheck(sku,index,index1)"/>
							  <icon v-else type="circle" @tap="sigleCheck(sku,index,index1)"/>
							</view>
							<view class="flex " style="flex:1" @tap="goodsDetail(sku.goods_id)">
								<view class="cu-avatar radius" :style="'background-image:url('+sku.goods_image+');width:90px;height:90px'"></view>
								<view class="content margin-left flex-column justify-start" style="height: 180upx;">
									<view class="flex align-start">
										<view class="text-df" style="line-height: 30upx;font-weight: 600;padding-top:10px;">{{sku.name}}</view>
									</view>
									<view class="text-gray" v-if="sku.spec_list[0]">
										<text class="radius" style="background-color: #eee;padding: 3px 4px;font-size: 22upx;">
											{{sku.spec_list[0].spec_value}}{{sku.spec_list[0].spec_name}}
										</text>
									</view>
									<view class='flex justify-between margin-top'>
										<text class='goodsPrice'>￥{{sku.original_price | formatPrice}}</text>
									</view>
								</view>
							</view>
							<view class="flex justify-end align-center margin-right-sm" style="width: 100%;">
								<view class="flex align-center" style="border-radius: 6rpx;overflow: hidden;">
									<view class="cart-stepper" @tap="minus(sku,index)">
										<view class="sbtn cuIcon-move text-black"></view>
									</view>
									<view class="cart-stepper text-black">
										<view class="text-sm cartnum" v-model="sku.num">{{sku.num}}</view>
									</view>
									<view class="cart-stepper" @tap="plus(sku,index)">
										<view class="sbtn cuIcon-add text-black"></view>
									</view>
								</view>
							</view>
							<view class="move" @tap="DEL_Order(sku.sku_id)">
								<view class="bg-red">删除</view>
							</view>
						</view>
					</view>
				</view>
			</view>
		</mescroll-uni>
		<view v-if="cartList.length>0">
			<view class="cu-bar bg-white tabbar foot border shop">
				<view class='allCheck' style="width:80px;">
					<icon v-if="selectAllStatus" type="success" color="#CB1414" @tap="selectAll"/>
					<icon v-else type="circle" color="#CCC" @tap="selectAll"/>
					<text class="allText">全选</text>
				</view>
				<view v-if="izEdit" class="flex justify-end align-center padding">
					<view class="cartBtn"  @tap="emptyCart">清空</view>
					<view class="cartBtn margin-left" @tap="DEL_Order">删除</view>
				</view>
				<view v-else class="padding flex justify-between" style="width: 100%;">
					<view class="flex align-center">
						<view class="text-sm">合计:</view><view class="text-bold text-df text-black">￥{{total_price | formatPrice}}</view>
					</view>
					<button class="cu-btn bg-red round " @tap="onClickButton">立即购买</button>
				</view>
			</view>	
		</view>
	</view>
</template>

<script>
	import * as Cart_API from '@/api/cart.js'
	import * as Foundation from '@/utils/Foundation.js'
	import MescrollMixin from "@/components/mescroll-uni/mescroll-mixins.js";
	import MescrollMoreItemMixin from "@/components/mescroll-uni/mixins/mescroll-more-item.js";
	export default {
		mixins: [MescrollMixin,MescrollMoreItemMixin], 
		data() {
			return {
				izEdit:false,
				isTop: true,
				bottomBar:true,           //默认底部导航
				hasList: false,          // 列表是否有数据
				selectAllStatus: false,    // 全选状态，默认全选
				totalPrice:0,    //总价
				cartList:[],
				total_price:0,
				seletedList:[],
				list:0 ,//购物车数量,
				buyGoodsNum:0,
				modalName: null,
				listTouchStart: 0,
				listTouchDirection: null,
				id:'',
				state: 2,
				addList:[],
				CartData:[],
				izLogin:false,
				downOption:{
					auto:false
				},
				upOption:{
					auto:false,
					noMoreSize: 8,
					empty:{
						icon:'/static/images/empty/empty_cart.png',
						tip: '您的购物车还是空的，快添加一个吧'
					}
				},
				sku_ids:''
			};
		},
		onShow() {
			let token =uni.getStorageSync('token')
			if(token){
				this.upCallback()
				this.izLogin = true
			}else{
				this.izLogin = false
			}
		},
		watch:{
			selectAllStatus(newVal){
				this.selectAllStatus = newVal
			},
			izLogin(newVal){
				this.izLogin =newVal
			}
		},
		methods:{
			onShareAppMessage() {
				let page_path = '/pages/home/home'
				let mobile = uni.getStorageSync('userInfo').mobile
				let user = uni.getStorageSync('userInfo').nickname
				let shop_name = uni.getStorageSync('shop').shop_name
				let shop_id = uni.getStorageSync('shop').shop_id
				let title = ''
				let path = ''
				if(mobile && shop_id){
					title = user + '分享的'+shop_name
					path = page_path+'?shop_id='+shop_id+'&sharePhone='+mobile
				}else if(shop_id){
					title = shop_name
					path =  page_path+'?shop_id='+shop_id
				}
			    return {
					title: title,
					path: path
			    }
			},
			/*下拉刷新的回调 */
			downCallback() {
				// this.params.keyword = ''
				this.mescroll.resetUpScroll()
			},
			upCallback(page) {
				// this.GET_CartList()
				let that = this
				let params = {
					sellerId:uni.getStorageSync('shop').shop_id 
				}
				Cart_API.GetAllCart(params).then(res =>{
					this.mescroll.endSuccess(res.cart_list.length)
					let sku_ids =[]
					this.cartList=[]
					this.CartData = res 
					this.cartList = res.cart_list
					this.total_price = res.total_price.total_price
					if(res.cart_list){
						let checked = true
						res.cart_list.map(item =>{
							item.sku_list.map(key =>{
								if(key.checked === 0){
									checked = false
								}else{
									// console.log(key)
									sku_ids.push(key.sku_id)
								}
							})
							this.list+=1
						})
						if(checked){
							this.selectAllStatus = true
						}else{
							this.selectAllStatus = false
						}
					}
					this.sku_ids = sku_ids.join(',')
				}).catch(()=>{
					this.mescroll.endErr() 
				})
			},
			//点击空布局按钮的回调
			emptyClick(){
				uni.showToast({
					title:'点击了按钮,具体逻辑自行实现'
				})
			},
			changeEdit(){
				if(this.izLogin){
					this.izEdit = !this.izEdit
				}
			},
			goLogin(){
				if(!uni.getStorageSync('isCanUse')){
					uni.navigateTo({url:'../login/login'})
				}else{
					uni.navigateTo({url: '../login/register'})
				}
			},
			goodsDetail(goods_id){
				uni.navigateTo({
					url:"/pages/goods/index?goods_id="+goods_id
				})
			},
			GET_CartList(){
				
			},
			// 减去商品
			minus(item,index){
				if(item.num<=1){
					return;
				}
				let params = {
					num :item.num-1
				}
				this.CartUpdate(item.sku_id,params)							 // 重新获取总价
			},
			// 加
			plus(item,index){
				if((item.num+1) <= item.enable_quantity){
					let params = {
						 num : item.num+1
					}
					setTimeout(()=>{
						this.CartUpdate(item.sku_id,params)
					},200)
				}else{
					uni.showToast({
						icon:'none',
						title:'此商品已经超出库存，现库存数量为'+ item.enable_quantity,
						duration:2000
					})
				}
			},
			// 单选
			sigleCheck(sku,selleridx,skuidx){
			   let checked
			   if(sku.checked===1) checked = 0
			   else checked =1
			   let parmas = {
				   checked : checked,
				   num :sku.num
			   }
			   this.CartUpdate(parseInt(sku.sku_id),parmas)                         // 重新获取总价
			},
			CartUpdate(sku_id,params){
				Cart_API.CartUpdate(sku_id,params).then(res =>{
					this.upCallback()
				}).catch((rej)=>{
				})
				// setTimeout(()=>{wx.hideLoading()},500)
			},
			 // 全选
			selectAll(e) {
				this.selectAllStatus = !this.selectAllStatus
				let params = {
				   checked:this.selectAllStatus?1:0,
				}
				Cart_API.CartCheckAll(params).then(res =>{
					this.upCallback()
				})
			},
			// x
			emptyCart(){
				uni.showModal({
					title: '删除提示',
					content: '您确定要清空购物车吗?',
					success: (res)=>{
						if (res.confirm) {
							Cart_API.DeleteCart().then(res =>{
								uni.showToast({
									icon:'success',
									title:'已清空'
								})
								let cartList = this.cartList
								cartList = ''
								this.cartList = cartList
								this.upCallback()
							})
						}
					}
				})
			},
			// 购买成功
			onClickButton() {
				let params = {
					sellerId : uni.getStorageSync('shop').shop_id
				}
				Cart_API.GetCartDetail(params).then(res =>{
					if(res.cart_list.length<1){
						uni.showToast({
							title:'请选择商品',
							duration:2000
						})
					}else{
						let CartData = res
						uni.setStorage({
							key:'buylist',
							data:CartData,
							success: () => {
								uni.navigateTo({
									url:'../order/orderComfirm'
								})
							}
						})
					}
				})
			},
			Gohome(){
			  uni.switchTab({
			    url: '../home/home'
			  })
			},
			// ListTouch触摸开始
			ListTouchStart(e) {
				this.listTouchStart = e.touches[0].pageX
			},
			// ListTouch计算方向
			ListTouchMove(e) {
				this.listTouchDirection = e.touches[0].pageX - this.listTouchStart+40 > 0 ? 'right' : 'left'
			},
			// ListTouch计算滚动
			ListTouchEnd(e) {
				if (this.listTouchDirection == 'left') {
					this.modalName = e.currentTarget.dataset.target
				} else {
					this.modalName = null
				}
				this.listTouchDirection = null
			},
			// 删除商品(含多个商品删除)
			DEL_Order(sku_id){
				uni.showModal({
					title: '',
					content: '你确定将选中的商品移除购物车吗?',
					success: (res)=>{
						if (res.confirm) {
							let sku_ids
							if(!this.izEdit){
								sku_ids = sku_id
							}else{
								sku_ids = this.sku_ids
							}
							Cart_API.DeleteCartGoods(sku_ids).then(res =>{
								uni.showToast({
									icon:'success',
									title:'移除成功'
								})
								this.upCallback()
							})
						}
					}
				})
			}	
		}
	}
</script>

<style lang="scss">
	/deep/ .cu-list>.cu-item .move {
		width: 120upx;
	}
	/deep/ .cu-list>.cu-item.move-cur {
		transform: translateX(-120upx)
	}
.cart{
  background: $background-container;
  height: 100vh;
}
.top{
  color: #666;
  background: #fff;
  padding: 20upx 20upx;
  font-size: 32upx;
  display: flex;
  justify-content: space-between;
}
.top .wap-nav{
  vertical-align: middle;
  padding-right:16upx;
}
.delete{
  padding-right:16upx;
  margin-left: 20upx; 
}
.compute,.cartGoods{
  display: flex;
  align-cartList: center;
}
.cartGoods{
  justify-content: space-between;
}
.cartGoods{
  background: #fff;
  margin-top: 20upx;
  padding: 10px 0;
}
.goodsImg image{
  width: 160upx;
  height: 160upx
}

.goodsDetail{
  margin:0 30upx;
  flex: 1;
}
.goodsName{
  color: #666;
 font-size: 28upx;
  width: 51%;
}
.details{
  height: 100%;
  overflow: hidden;
  display: flex;
}
.goodsPrice{
 font-size: 30upx;
  color: red;
  font-weight: bold;
}
.operate{
  display: flex;
  height: 60upx;
  justify-content: space-around;
  font-size: 20upx;
}
.sigleCheck{
  margin: 0 20upx;
}
.allCheck{
  margin-left: 20upx;
}
.allCheck icon{
  vertical-align: middle;
  padding-right:10upx;
}
.Gohome .van-button--large{
  height: 70upx;
  width: 240upx;
  background: $color-main;
  border: 1px solid $color-main;
  line-height: 68px;
  font-size: 32upx;
}
/deep/.cu-list.menu>.cu-item:after {
		border-bottom: none;
		height: 60upx;
	}
	/deep/.cu-list.menu>.cu-item  {
	min-height: 80rpx;
	}
	/deep/.cu-list.menu>.cu-item .content>text[class*=cuIcon] {
		width: 18px;
		text-align: left;
	}
	/deep/.cu-list+.cu-list {
		margin-top: 0;
	}
	.cart-stepper{
		background: #f3f3f3;
		// margin-left:4rpx;
		// border-radius: 6rpx;
		height: 40rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		.cartnum{
			border-left: 5rpx solid #fff;
			border-right: 5rpx solid #fff;
			padding:10rpx 14rpx;
		}
		.sbtn{
			padding:10rpx 4rpx;
			color: #333;
		}
	}
.cartBtn{
	padding: 10rpx 30rpx;
	border: 1px solid #999;
	border-radius: 12rpx;
}
</style>